package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    //客户端发送的是post请求  所以要用@RequestBody
    @PostMapping("/login")
    //登录
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //1.把参数传递给service
        R<Employee> result = employeeService.login(employee);

        //2.判断是否登录成功，成功的时候session需要做登录成功标记
        if (result.getCode()==1){
            session.setAttribute("employee",result.getData().getId());
        }
        //3.返回结果
        return result;
    }

    @PostMapping("/logout")
    //退出
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    //添加员工
    public R<String> insert(@RequestBody Employee employee,HttpSession session){
        //接收添加员工信息
        //1. 获取当前登陆的用户,
        Long empId = (Long) session.getAttribute("employee");
        //补全员工的创建者与修改者
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        //2. 把数据交给service
        employeeService.insert(employee);
        return R.success("保存成功");
    }


    //员工分页
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize,String name){
        Page<Employee> pageResult = employeeService.findBypage(page,pageSize,name);
        return R.success(pageResult);

    }


    //修改用户数据
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        //1.获取当前登录用户
        Long empId = (Long) session.getAttribute("employee");

        //2.给Employee补全参数
        employee.setUpdateUser(empId);
        employeeService.update(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        R<Employee> result = employeeService.findById(id);
        return result;
    }
}
